<template>
  <div class="translation-page">
    <el-scrollbar class="translation-manager">
      <el-card class="toolbar-card" shadow="hover">
        <div class="toolbar">
          <div class="search-group">
            <el-input
              v-model="searchForm.en"
              placeholder="英文关键词"
              prefix-icon="Search"
              class="search-input"
              size="default"
            />
            <el-input
              v-model="searchForm.cn"
              placeholder="中文关键词"
              prefix-icon="Search"
              class="search-input"
              size="default"
            />
            <el-button type="primary" size="default" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button size="default" @click="resetSearch">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </div>

          <div class="action-group">
            <el-upload
              :show-file-list="false"
              accept=".csv"
              :before-upload="handleImport"
              class="upload-btn"
            >
              <el-button size="default" type="success">
                <el-icon><Upload /></el-icon>
                导入
              </el-button>
            </el-upload>

            <el-button
              size="default"
              type="warning"
              @click="handleExport"
              :loading="taskStatus.loading"
            >
              <el-icon><Download /></el-icon>
              导出
            </el-button>

            <el-button size="default" type="primary" @click="openAddDialog">
              <el-icon><Plus /></el-icon>
              新增
            </el-button>
            <el-button size="default" type="danger" @click="deleteFilter" icon="Search" class="search-btn">{{ $t('message.common.deleteFilter') }}</el-button>
          </div>
        </div>

        <!-- 第二行：分页和高级筛选按钮 -->
        <div class="toolbar-secondary">
          <el-button
            size="default"
            text
            @click="showAdvancedFilter = !showAdvancedFilter"
            class="toggle-advanced"
          >
            {{ showAdvancedFilter ? '收起筛选' : '高级筛选' }}
            <el-icon :size="16">
              <ChevronDown :rotate="showAdvancedFilter ? 180 : 0" />
            </el-icon>
          </el-button>
          
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.page_size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :hide-on-single-page="false"
            size="default"
          />
        </div>

        <!-- 高级筛选内容（在按钮下方展开） -->
        <div class="advanced-filter-container" v-if="showAdvancedFilter">
          <div class="advanced-filter">
            <div style="display: flex; gap: 10px;">
              <el-input-number
                style="width: 100px;"
                v-model="searchForm.hit_count_min"
                placeholder="最小命中次数"
                :min="0"
                size="default"
              />
              <el-input-number
                style="width: 100px;"
                v-model="searchForm.hit_count_max"
                placeholder="最大命中次数"
                :min="0"
                size="default"
              />
              <el-select
                style="width: 100px;"
                v-model="searchForm.sort_field"
                placeholder="排序字段"
                size="default"
              >
                <el-option label="英文" value="en" />
                <el-option label="中文" value="cn" />
                <el-option label="命中次数" value="hit_count" />
                <el-option label="创建时间" value="created_at" />
              </el-select>
              <el-select
                style="width: 100px;"
                v-model="searchForm.sort_order"
                placeholder="排序方式"
                size="default"
              >
                <el-option label="升序" value="ASC" />
                <el-option label="降序" value="DESC" />
              </el-select>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 表格内容 -->
      <el-card class="table-card" shadow="hover" style="margin-top: 16px;">
        <el-table
          v-loading="tableLoading"
          :data="tableData"
          border
          stripe
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="en" label="英文" min-width="200" />
          <el-table-column prop="cn" label="中文" min-width="200" />
          <el-table-column prop="hit_count" label="命中次数" width="120">
            <template #default="scope">
              <el-badge :value="scope.row.hit_count" :max="9999" type="primary" />
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="180" />
          <el-table-column prop="updated_at" label="更新时间" width="180" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button
                size="default"
                type="primary"
                text
                @click="openEditDialog(scope.row)"
              >
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button
                size="default"
                type="danger"
                text
                @click="handleDelete(scope.row.en)"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 对话框部分保持不变 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '新增翻译' : '编辑翻译'"
        :width="dialogWidth"
      >
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="80px"
        >
          <el-form-item label="英文" prop="en" :disabled="dialogType === 'edit'">
            <el-input v-model="formData.en" placeholder="请输入英文" />
          </el-form-item>
          <el-form-item label="中文" prop="cn">
            <el-input v-model="formData.cn" placeholder="请输入中文翻译" />
          </el-form-item>
          <el-form-item label="命中次数" prop="hit_count">
            <el-input-number
              v-model="formData.hit_count"
              :min="0"
              placeholder="请输入命中次数"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleDialogConfirm">确认</el-button>
        </template>
      </el-dialog>

      <el-dialog
        v-model="batchDialogVisible"
        title="批量操作"
        width="300px"
        :close-on-click-modal="false"
      >
        <div class="batch-operations">
          <p>已选择 {{ selectedRows.length }} 条记录</p>
          <el-button
            type="danger"
            class="batch-delete-btn"
            @click="handleBatchDelete"
            :disabled="selectedRows.length === 0"
          >
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </div>
        <template #footer>
          <el-button @click="batchDialogVisible = false">关闭</el-button>
        </template>
      </el-dialog>

      <el-dialog
        v-model="taskStatus.progressVisible"
        :title="`${taskStatus.type === 'import' ? '导入' : '导出'}进度`"
        width="300px"
        :close-on-click-modal="false"
        :show-close="false"
      >
        <div class="task-progress">
          <el-progress
            :percentage="taskStatus.progress"
            stroke-width="6"
            :status="taskStatus.progress === 100 ? 'success' : 'active'"
          />
          <p class="progress-text">{{ taskStatus.progress }}%</p>
          <p v-if="taskStatus.progress < 100" class="progress-info">
            正在{{ taskStatus.type === 'import' ? '导入' : '导出' }}数据，请稍候...
          </p>
          <p v-if="taskStatus.progress === 100" class="progress-info">
            {{ taskStatus.type === 'import' ? '导入' : '导出' }}完成
            <span v-if="taskStatus.type === 'export'">，即将下载文件</span>
          </p>
        </div>
      </el-dialog>
    </el-scrollbar>
  </div>
</template>

<script setup lang="ts">
// 脚本部分保持不变，与之前完整方案一致
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { translateApi } from '@renderer/api/translate';

// 表格数据和加载状态
const tableData = ref([]);
const tableLoading = ref(true);
const selectedRows = ref([]);

// 搜索表单
const searchForm = reactive({
  en: '',
  cn: '',
  hit_count_min: undefined,
  hit_count_max: undefined,
  sort_field: 'hit_count',
  sort_order: 'DESC' as 'ASC' | 'DESC'
});

// 分页信息
const pagination = reactive({
  page: 1,
  page_size: 10,
  total: 0,
  total_pages: 0
});

// 对话框状态
const dialogVisible = ref(false);
const dialogType = ref<'add' | 'edit'>('add');
const dialogWidth = computed(() => window.innerWidth < 768 ? '90%' : '500px');

// 表单数据和规则
const formData = reactive({
  en: '',
  cn: '',
  hit_count: 0
});

const formRules = reactive({
  en: [
    { required: true, message: '请输入英文', trigger: 'blur' }
  ],
  cn: [
    { required: true, message: '请输入中文翻译', trigger: 'blur' }
  ],
  hit_count: [
    { required: true, message: '请输入命中次数', trigger: 'blur' },
    { type: 'number', min: 0, message: '命中次数不能为负数', trigger: 'blur' }
  ]
});

const formRef = ref();

// 高级筛选
const showAdvancedFilter = ref(false);

// 批量操作对话框
const batchDialogVisible = ref(false);

// 统一任务状态管理
const taskStatus = reactive({
  type: 'import' as 'import' | 'export',
  loading: false,
  progressVisible: false,
  progress: 0,
  taskId: '',
  progressTimer: null as NodeJS.Timeout | null
});

// 初始化
onMounted(() => {
  fetchTranslateData();
});

// 进度查询函数
const fetchTaskProgress = async () => {
  try {
    if (!taskStatus.taskId) return;

    const response = await translateApi().getTaskProgress(taskStatus.taskId);
    taskStatus.progress = response.data.progress;

    if (response.data.progress === 100 || response.data.progress === -1) {
      clearProgressTimer();
      if(taskStatus.type === 'import'){
        fetchTranslateData();
      }
      setTimeout(() => {
        taskStatus.progressVisible = false;
        taskStatus.loading = false;
      }, 1000);
    }
  } catch (error) {
    console.error(`获取${taskStatus.type === 'import' ? '导入' : '导出'}进度失败:`, error);
    clearProgressTimer();
    taskStatus.progressVisible = false;
    taskStatus.loading = false;
  }
};

const clearProgressTimer = () => {
  if (taskStatus.progressTimer) {
    clearInterval(taskStatus.progressTimer);
    taskStatus.progressTimer = null;
  }
};

// 获取翻译数据
const fetchTranslateData = async () => {
  try {
    tableLoading.value = true;
    const params = {
      ...searchForm,
      page: pagination.page,
      page_size: pagination.page_size
    };

    const response = await translateApi().getTranslatePaged(params);
    tableData.value = response.data.data;
    pagination.total = response.data.pagination.total;
    pagination.total_pages = response.data.pagination.total_pages;
  } catch (error) {
    console.error('获取翻译数据失败:', error);
    ElMessage.error('获取数据失败，请重试');
  } finally {
    tableLoading.value = false;
  }
};

const deleteFilter = async ()=>{
  try {
    await ElMessageBox.confirm('确定删除当前筛选的标签？', '警告', { type: 'warning' })
    const params = {
      ...searchForm,
      page: pagination.page,
      page_size: pagination.page_size
    };
    translateApi().deleteTranslatesByFilter(params).then(res => {
      if(res.data.success){
        ElMessage.success(JSON.stringify(res.data))
        fetchTranslateData()
      }
      else{
        ElMessage.error(JSON.stringify(res.data))
      }
    })
  } catch (error) {
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  fetchTranslateData();
};

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    en: '',
    cn: '',
    hit_count_min: undefined,
    hit_count_max: undefined,
    sort_field: 'hit_count',
    sort_order: 'DESC'
  });
  pagination.page = 1;
  fetchTranslateData();
};

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.page_size = size;
  fetchTranslateData();
};

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.page = page;
  fetchTranslateData();
};

// 选择项变化
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows;
};

// 打开新增对话框
const openAddDialog = () => {
  dialogType.value = 'add';
  Object.assign(formData, {
    en: '',
    cn: '',
    hit_count: 0
  });
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (row: any) => {
  dialogType.value = 'edit';
  Object.assign(formData, {
    en: row.en,
    cn: row.cn,
    hit_count: row.hit_count
  });
  dialogVisible.value = true;
};

// 对话框确认
const handleDialogConfirm = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    if (dialogType.value === 'add') {
      await translateApi().addTranslate(formData);
      ElMessage.success('新增成功');
    } else {
      await translateApi().updateTranslate(formData);
      ElMessage.success('更新成功');
    }

    dialogVisible.value = false;
    fetchTranslateData();
  } catch (error) {
    console.error('提交失败:', error);
    if (error.name !== 'ValidationError') {
      ElMessage.error('操作失败，请重试');
    }
  }
};

// 删除
const handleDelete = async (en: string) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除英文为"${en}"的翻译记录吗？`,
      '确认删除',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    await translateApi().deleteTranslate({ en });
    ElMessage.success('删除成功');
    fetchTranslateData();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败，请重试');
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的${selectedRows.value.length}条记录吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    for (const row of selectedRows.value) {
      await translateApi().deleteTranslate({ en: row.en });
    }

    ElMessage.success('批量删除成功');
    batchDialogVisible.value = false;
    fetchTranslateData();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error);
      ElMessage.error('批量删除失败，请重试');
    }
  }
};

// 导入
const handleImport = async (file: File) => {
  try {
    taskStatus.type = 'import';
    taskStatus.loading = true;
    taskStatus.progress = 0;
    taskStatus.progressVisible = true;
    taskStatus.taskId = `import_${Date.now()}`;

    taskStatus.progressTimer = setInterval(() => {
      if (taskStatus.progressVisible && taskStatus.taskId) {
        fetchTaskProgress();
      }
    }, 200);

    const formData = new FormData();
    formData.append('file', file);
    formData.append('taskId', taskStatus.taskId);

    const res = await translateApi().importTranslateCsv(formData);
    
    if (res.data.success) {
      ElMessage.success('翻译表导入任务已启动');
    } else {
      taskStatus.progressVisible = false;
      ElMessage.error(JSON.stringify(res.data) || '导入失败');
      clearProgressTimer();
    }

    return false;
  } catch (error) {
    ElMessage.error('导入失败');
    clearProgressTimer();
    taskStatus.progressVisible = false;
    taskStatus.loading = false;
    return false;
  }
};

// 导出
const handleExport = async () => {
  try {
    taskStatus.type = 'export';
    taskStatus.loading = true;
    taskStatus.progress = 0;
    taskStatus.progressVisible = true;
    taskStatus.taskId = `export_${Date.now()}`;

    taskStatus.progressTimer = setInterval(() => {
      if (taskStatus.progressVisible && taskStatus.taskId) {
        fetchTaskProgress();
      }
    }, 200);

    const params = {
      ...searchForm,
      taskId: taskStatus.taskId
    };
    const response = await translateApi().exportTranslateStream(params);

    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `translations_${new Date().getTime()}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    clearProgressTimer();
    await fetchTaskProgress();
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出失败，请重试');
    clearProgressTimer();
    taskStatus.progressVisible = false;
  } finally {
    if (taskStatus.progress === 100 || taskStatus.progress === -1) {
      taskStatus.loading = false;
    }
    clearProgressTimer();
  }
};
</script>

<style scoped lang="scss">
.translation-page {
  width: 100%;
  min-height: 100vh;
  padding: 16px;
  box-sizing: border-box;
}

.translation-manager {
  padding: 16px;
  background-color: var(--el-bg-color-page);
  height: calc(100vh - 60px);
  min-height: 500px;
}

.toolbar-card {
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 16px;
  padding: 16px;
}

// 第一行工具栏
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

// 第二行工具栏（分页和筛选按钮）
.toolbar-secondary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 8px;
}

.search-group {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.search-input {
  width: 200px;
}

.action-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.upload-btn {
  display: inline-block;
}

// 高级筛选样式
.advanced-filter-container {
  position: relative;
  margin-top: 12px;
  animation: fadeIn 0.3s ease;
  z-index: 10;
}

.advanced-filter {
  padding: 12px;
  background-color: var(--el-fill-color-light);
  border-radius: 6px;
}

.toggle-advanced {
  padding: 4px 0;
  color: var(--el-text-color);
  display: flex;
  align-items: center;
  gap: 4px;
}

.table-card {
  border-radius: 8px;
  overflow: hidden;
  position: relative;
  min-height: 300px;
}

.batch-operations {
  padding: 10px 0;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.batch-delete-btn {
  width: 100%;
}

/* 进度样式 */
.task-progress {
  padding: 20px 0;
}

.progress-text {
  text-align: center;
  margin: 10px 0;
  font-weight: 500;
}

.progress-info {
  text-align: center;
  color: var(--el-text-color-placeholder);
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-input {
    width: 100%;
  }

  .toolbar, .toolbar-secondary {
    flex-direction: column;
    align-items: stretch;
  }

  .search-group, .action-group {
    width: 100%;
    justify-content: stretch;
  }

  .action-group {
    justify-content: space-between;
  }
  
  .el-pagination {
    width: 100%;
    justify-content: center;
  }
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}
</style>
